package com.zzyl.nursing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.thread.UserTheadLocal;
import com.zzyl.nursing.domain.pojo.Reservation;
import com.zzyl.nursing.mapper.ReservationMapper;
import com.zzyl.nursing.service.ReservationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements ReservationService {
    @Autowired
    private ReservationMapper reservationMapper;

    @Override
    public Integer getCancelledCount(Long userId, LocalDateTime startTime, LocalDateTime endTime) {
        Reservation reservation = new Reservation();
      // 使用userId匹配预约人ID
        reservation.setStatus(2);

        // 构造查询条件
        LambdaQueryWrapper<Reservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Reservation::getCreateBy, UserTheadLocal.getUser());  // 使用createBy匹配创建人ID
        queryWrapper.eq(Reservation::getStatus, 2);         // 状态为2表示已取消
        queryWrapper.ge(Reservation::getUpdateTime, startTime);  // 更新时间大于等于开始时间
        queryWrapper.lt(Reservation::getUpdateTime, endTime);    // 更新时间小于结束时间

        return Math.toIntExact(reservationMapper.selectCount(queryWrapper));
    }

    @Override
    public Integer getReservationCountByTime(String startTime, String endTime) {
        // 构造查询条件
        LambdaQueryWrapper<Reservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(Reservation::getTime, startTime);  // 开始时间大于等于开始时间
        queryWrapper.lt(Reservation::getTime, endTime);    // 开始时间小于结束时间
        queryWrapper.eq(Reservation::getStatus, 0);             // 状态为0表示预约中

        return Math.toIntExact(reservationMapper.selectCount(queryWrapper));
    }

    @Override
    public boolean saves(Reservation reservation) {
        List<Reservation> list = this.lambdaQuery().eq(Reservation::getMobile, reservation.getMobile())
                .in(Reservation::getStatus, 0, 1).list();
        if (list.size() == 0) {
             this.save(reservation);
             return true;
        }
        return false;
    }



}